import React from 'react';
import Styles from './styles';
import {ScrollView, Text, View} from 'react-native';
import ThemeStyles from '../../styles';
import InputItem from '../../components/input-item';
import Button from '../../components/button';
import {bindActionCreators} from 'redux';
import * as registerActionCreator from '../../actions/register-action';
import {connect} from 'react-redux';
import {getRealSize, Touchable} from '../../utils';
import Toast from '../../components/toast';
import {UserType} from '../../reducers/user';
import Validator from 'async-validator';
import FileUpload, {UploadState} from '../../components/file-upload';
import config from '../../../config.json';
import {I18n} from '../../reducers/intl';

class ApplicationMaterialScreen extends React.Component {
  static navigationOptions = ({navigation}) => ({
    title: I18n.t('page.title.paper'),
    headerLeft: () => (
      <Touchable onPress={() => navigation.popToTop()}>
        <View style={[ThemeStyles.Layout.base.padding]}>
          <Text style={[ThemeStyles.Front.base]}>
            {I18n.t('button.cancel')}
          </Text>
        </View>
      </Touchable>
    ),
    headerRight: () => (
      <Touchable onPress={() => navigation.pop()}>
        <View
          style={[ThemeStyles.Layout.base.padding, {height: getRealSize(48)}]}>
          <Text style={[ThemeStyles.Front.base]}>
            {I18n.t('button.previous')}
          </Text>
        </View>
      </Touchable>
    ),
  });

  constructor() {
    super();
    this.validator = new Validator({
      name: {
        required: true,
        message: I18n.t('form.validate.message.name'),
      },
      cert: {
        required: true,
        message: I18n.t('form.validate.message.paper'),
      },
    });
  }

  state = {
    location: {},
  };

  componentDidMount() {
    const {registerActions, appState} = this.props;
    if (appState.location) {
      registerActions.update({
        country: appState.location.country,
        address_1: appState.location.address,
      });
    }
  }

  onSubmit = async () => {
    const {navigation, form, registerActions, user} = this.props;
    try {
      await this.validator.validate(form);
      await registerActions.submitCert(form, user);
      // navigation.popToTop();
    } catch (e) {
      if (e.errors) {
        Toast.show(e.errors[0].message);
      } else {
        Toast.show(e.message);
      }
      this.setState({
        allowSubmit: false,
        errors: e,
      });
    }
  };

  onNext = async () => {
    const {navigation, form} = this.props;
    try {
      await this.validator.validate(form);
      navigation.navigate('ProductSetting');
    } catch (e) {
      if (e.errors) {
        Toast.show(e.errors[0].message);
      } else {
        Toast.show(e.message);
      }
      this.setState({
        allowSubmit: false,
        errors: e,
      });
    }
  };

  onChangeValue = async (value, field) => {
    const {form, registerActions} = this.props;
    registerActions.update({[field]: value});
    const dataForm = {
      ...form,
      [field]: value,
    };
    try {
      await this.validator.validate(dataForm);
      this.setState({
        allowSubmit: true,
        errors: [],
      });
    } catch (errors) {
      this.setState({
        allowSubmit: false,
        errors,
      });
    }
  };

  // onChangeFile = file => {
  //   const {registerActions} = this.props;
  //   registerActions.update({cert: {...file}});
  // };
  //
  // onProgress = (jobId, percentage) => {
  //   const {form, registerActions} = this.props;
  //   const file = {
  //     ...form.cert,
  //     rate: Number(percentage / 100).toFixed(2),
  //     state: UploadState.UPLOADING,
  //   };
  //   registerActions.update({cert: {...file}});
  // };

  onUploadSuccess = (result) => {
    const {form, registerActions} = this.props;
    const file = {...form.cert, ...result, state: UploadState.DONE};
    registerActions.update({cert: {...file}});
  };

  render() {
    const {form, token, navigation} = this.props;
    return (
      <ScrollView
        style={Styles.pageContainer}
        showsHorizontalScrollIndicator={false}
        showsVerticalScrollIndicator={false}>
        <View style={[ThemeStyles.Layout.base.mh, ThemeStyles.Layout.base.mt]}>
          <InputItem
            placeholder={I18n.t('form.placeholder.name')}
            isRequire
            value={form.name}
            onChange={value => this.onChangeValue(value, 'name')}
          />
        </View>
        <View style={[ThemeStyles.Layout.base.mh, ThemeStyles.Layout.base.mt]}>
          <InputItem
            placeholder={I18n.t('form.placeholder.tel')}
            value={form.tel}
            onChange={value => this.onChangeValue(value, 'tel')}
          />
        </View>
        <View style={[ThemeStyles.Layout.base.mh, ThemeStyles.Layout.base.mt]}>
          <InputItem
            placeholder={I18n.t('form.placeholder.country')}
            value={form.country}
            icon="search-location"
            editable={false}
            onFocus={() =>
              navigation.navigate('RegisterLocation', {register: true})
            }
          />
        </View>
        <View style={[ThemeStyles.Layout.base.mh, ThemeStyles.Layout.base.mt]}>
          <InputItem
            placeholder={I18n.t('form.placeholder.address')}
            value={form.address_1}
            editable={false}
            onFocus={() =>
              navigation.navigate('RegisterLocation', {register: true})
            }
          />
        </View>
        <View style={[ThemeStyles.Layout.base.mh, ThemeStyles.Layout.base.mt]}>
          <FileUpload
            token={token.access}
            uploadUrl={`${config.httpClient.host}/web/image/new`}
            files={form.cert ? [form.cert] : []}
            // onChange={this.onChangeFile}
            // onProgress={this.onProgress}
            onSuccess={this.onUploadSuccess}
            addLabel={I18n.t('form.label.upload')}
          />
        </View>
        <View style={[ThemeStyles.Layout.base.mh, ThemeStyles.Layout.base.mt]}>
          {[UserType.clinic, UserType.dentist].includes(form.role) ? (
            <Button label={I18n.t('button.submit')} onPress={this.onSubmit} />
          ) : (
            <Button label={I18n.t('button.next')} onPress={this.onNext} />
          )}
        </View>
      </ScrollView>
    );
  }
}
const mapStateToProps = state => ({
  appState: state.appState,
  device: state.device,
  user: state.user,
  token: state.token,
  form: state.registerForm,
});

const mapDispatchToProps = dispatch => ({
  registerActions: bindActionCreators(registerActionCreator, dispatch),
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(ApplicationMaterialScreen);
